package com.yupi.springbootinit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.entity.Tag;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.service.TagService;
import com.yupi.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 标签接口
 *
 */
@RestController
@RequestMapping("/tags")
@Slf4j
@CrossOrigin
public class TagsController {

    @Resource
    private TagService tagService;

    @Resource
    private UserService userService;

    @PostMapping("/addTags")
    public BaseResponse<Long> addTags(Tag tag, HttpServletRequest request) {
        Tag tags = new Tag();
        Long tagId = tag.getId();
        tags.setId(tagId);
        Integer isParent = tag.getIsParent();
        String tagName = tag.getTagName();
        if (isParent == 1) {
            tags.setIsParent(1);
            tags.setTagName(tagName);
            tagService.save(tags);
        }else{
            Long parentId = tag.getParentId();
            tags.setIsParent(0);
            tags.setParentId(parentId);
            tags.setTagName(tagName);
            tagService.save(tags);
        }
        return ResultUtils.success(tags.getId());
    }

    @GetMapping("/get/ParentsTags")
    public BaseResponse<List<Tag>> getParentsTags(HttpServletRequest request) {
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isParent", 1);
        queryWrapper.eq("isDeleted",0);
        List<Tag> tagList = tagService.list(queryWrapper);
        return ResultUtils.success(tagList);
    }

    @GetMapping("/get/Tags")
    public BaseResponse<List<Tag>> getTags(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        if (user==null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "未登录，请先登录");
        }
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        List<Tag> tagList = tagService.list(queryWrapper);
        return ResultUtils.success(tagList);
    }

    @GetMapping("/get/childTags")
    public BaseResponse<List<Tag>> getChildTags(String tagName,HttpServletRequest request) {
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tagName", tagName);
        Tag tag = tagService.getOne(queryWrapper);
        Long tagId = tag.getId();
        QueryWrapper<Tag> queryWrappers = new QueryWrapper<>();
        queryWrappers.eq("parentId",tagId);
        List<Tag> tagList = tagService.list(queryWrappers);
        return ResultUtils.success(tagList);
    }

}
